package com.wu.deadQueue;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.wu.rabbitmq.utils.RabbitMQUtils;
import lombok.SneakyThrows;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: RabbitMQ-Study
 * @author: 吴磊
 * @create: 2021-12-17 17:04
 * 死信队列实战
 * 消费者1
 */
public class Consumer01 {
    //普通交换机的名称
    private static final String NORMAL_EXCHANGE = "normal_exchange";
    //死信交换机的名称
    private static final String DEAD_EXCHANGE = "dead_exchange";
    //普通队列的名称
    private static final String NORMAL_QUEUE = "normal_queue";
    //死信队列的名称
    private static final String DEAD_QUEUE = "dead_queue";

    @SneakyThrows
    public static void main(String[] args) {
        Channel channel = RabbitMQUtils.getChannel();
        //声明普通交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        //声明死信交换机
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        //声明普通队列
        Map<String, Object> arguments = new HashMap<>();
        //过期时间 : 10s = 10000ms  一般由生产方设置，因为可以随意更改
        //arguments.put("x-message-ttl", 10000);
        //普通队列设置死信交换机
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        //设置死信routingKey   让死信交换机按这个关键字分发消息
        arguments.put("x-dead-letter-routing-key", "lisi");
        //设置普通队列的最大长度
        //arguments.put("x-max-length", 6);
        //channel.queueDelete(NORMAL_QUEUE, false, false);
        channel.queueDeclare(NORMAL_QUEUE, false, false, false, arguments);
        //声明死信队列
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);
        //绑定普通交换机与普通队列
        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, "zhangsan");
        //绑定死信交换机与死信队列
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, "lisi");
        System.out.println("Consumer01等待接收消息......");
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            if ("info-5".equals(msg)) {
                System.out.println("Consumer01等待消息：" + msg + "：此消息是被C1拒绝的");
                channel.basicReject(message.getEnvelope().getDeliveryTag(), false);
            } else {
                System.out.println("Consumer01接收消息：" + msg);
                channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
            }
        };
        //拒绝的时候要开启手动应答
        channel.basicConsume(NORMAL_QUEUE, false, deliverCallback, consumerTag -> {
        });

    }

}
